<?php

namespace app\common\service;

/**
 * 基类service
 * Class BaseServices
 * @package app\common\service
 */
class BaseServices
{
    /**
     * 下架
     * @var int
     */
    protected $isDelete = 1;

    /**
     * 正常
     * @var int
     */
    protected $noDelete = 0;

    /**
     * 组装like查询
     * @param $model
     * @param $searchField
     * @param $searchValue
     * @param array $fixFields
     */
    protected function formatLikeSearch(&$model, $searchField, $searchValue, $fixFields = ['title'])
    {
        if (!empty($searchField) && !empty($searchValue) && in_array($searchField, $fixFields)) {
            $model->whereLike($searchField, '%' . $searchValue .'%');
        }
    }

    /**
     * 设置分页
     * @param $model
     * @param int $page
     * @param int $pageSize
     */
    protected function formatPage(&$model, $page = 1, $pageSize = 15)
    {
        $start = ($page - 1) * $pageSize;
        $model->limit($start, $pageSize);
    }

    /**
     * 组装默认参数
     * @param $params
     */
    protected function formatData(&$params)
    {
        $default = [
            'is_delete' => $this->noDelete,
            'create_time' => time(),
            'update_time' => time(),
        ];
        $params = array_merge($params, $default);
    }

    /**
     * 格式化时间
     * @param array $params
     * @return array
     */
    protected function formatTime(array $params)
    {
        if (isset($params['create_time']) && is_int($params['create_time'])) {
            $params['create_time'] = date('Y-m-d H:i:s', $params['create_time']);
        }
        if (isset($params['update_time']) && is_int($params['update_time'])) {
            $params['update_time'] = date('Y-m-d H:i:s', $params['update_time']);
        }
        return $params;
    }
}
